import React, {useEffect, useState} from 'react';
import {Button, Card, Descriptions, Divider, Flex, message, Space, Tag} from 'antd';
import {EditOutlined, GiftOutlined, MoneyCollectOutlined, PlusOutlined, ShoppingCartOutlined} from '@ant-design/icons';
import styles from '../style.less';
import goodImg from '@/assets/images/gift.png'
import AddressSelection from "@/components/OrderPaymentModal/components/AddressSelection";
import AddAddressForm from "@/components/OrderPaymentModal/components/AddAddressForm";
import {
  addCustomerAddress,
  getDefaultOrMostUsed,
  listCustomerAddress
} from "@/pages/organization/customer-manager/api/customer-address";
import {IOrderData} from "@/components/OrderPaymentModal/types";
import {Typography} from 'antd';
import {API} from "@/services/typings";

const {Title} = Typography;

interface OrderInfoProps {
  data: IOrderData;
  loading: boolean;
  onSubmit: (address: API.ICustomerAddress) => void;
  customer: API.ICustomer
  initAddress?: API.ICustomerAddress
}

const OrderInfo: React.FC<OrderInfoProps> = ({data, loading, onSubmit, customer, initAddress}) => {

  const [addresses, setAddresses] = useState<API.ICustomerAddress[]>([]);
  const [selectedAddress, setSelectedAddress] = useState<API.ICustomerAddress | undefined>(initAddress);
  const [showAddressForm, setShowAddressForm] = useState(false);
  const [showAddressSelection, setShowAddressSelection] = useState(false);

  const handleAddressSelect = (address: API.ICustomerAddress) => {
    setSelectedAddress(address);
  };

  const handleAddAddress = async (values: API.ICustomerAddress) => {

    const {data: address} = await addCustomerAddress({...values, customerId: customer.id})
    setAddresses([...addresses, values]);
    setSelectedAddress(address);
    setShowAddressForm(false);
    message.success('地址添加成功');
  };

  const fetchAddress = async () => {
    // 请求所有的地址
    const {customer} = data
    const {data: addresses} = await listCustomerAddress({customerId: customer.id ?? -1})
    setAddresses(addresses);
    if (!initAddress){
      // 请求默认的地址
      const {data: defaultAddress} = await getDefaultOrMostUsed({customerId: customer.id ?? -1})
      setSelectedAddress(defaultAddress ?? null);
    }else {
      setSelectedAddress(initAddress);
    }
  }

  useEffect(() => {
    fetchAddress()
  }, []);

  return (
    <>
      <div className={styles.orderInfo}>
        <Card
          title={<Flex gap={'middle'}>
            <Title level={5}>{data.title}</Title>
          </Flex>}
          bordered={false}
        >
          <Descriptions column={1} className={styles.orderDescriptions}>
            <Descriptions.Item label="订单商品">
              <div className={styles.goodsList}>
                {data.items.map((item) => (
                  <div key={item.id} className={styles.goodsItem}>
                    <img
                      src={item.image ?? goodImg}
                      className={styles.goodsImage}
                      onError={(e) => {
                        e.currentTarget.src = goodImg; // 加载失败时回退到默认图片
                      }}
                      alt={item.image ?? goodImg}/>
                    <div className={styles.goodsInfo}>
                      <div className={styles.goodsName}>{item.name}</div>
                      <div className={styles.goodsMeta}>
                        <span>¥{item.amountUnit.toFixed(2)}</span>
                        <span>&nbsp;×&nbsp;{item.rechargeCount}</span>
                        {
                          item.giftCount ?
                            <Tag style={{marginLeft: 8}} color="gold" icon={<GiftOutlined/>}>
                              赠{item.giftCount}{item.unit ?? '件'}
                            </Tag> : ''
                        }
                        {
                          item.returnPrice ?
                            <Tag style={{marginLeft: 8}} color="orange" icon={<MoneyCollectOutlined/>}>
                              返现{item.returnPrice}元
                            </Tag> : ''
                        }
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </Descriptions.Item>
            <Descriptions.Item label="收货信息">
              {
                selectedAddress ? <Flex vertical>
                    <div>
                      {selectedAddress?.contactName}&nbsp;
                      {selectedAddress?.contactPhone}
                      <Button
                        type="link"
                        size="small"
                        icon={<EditOutlined/>}
                        onClick={() => setShowAddressSelection(true)}
                      />
                    </div>
                    <div>
                 <span>
                    {selectedAddress?.province}{selectedAddress?.city}{selectedAddress?.district}{selectedAddress?.detailedAddress}
                 </span>
                    </div>
                  </Flex> :
                  <Button
                    type="dashed"
                    icon={<PlusOutlined/>}
                    onClick={() => setShowAddressSelection(true)}
                    size="small"
                  >
                    请先选择地址
                  </Button>
              }

            </Descriptions.Item>
            <Descriptions.Item label="备注">{data.remark || '无'}</Descriptions.Item>
          </Descriptions>

          <Divider/>

          <div className={styles.orderSummary}>
            <div className={styles.summaryRow}>
              <span>商品总价</span>
              <span>¥{data.totalPayable ? data.totalPayable.toFixed(2) : '0.00'}</span>
            </div>
            <div className={styles.summaryRow}>
              <span>优惠</span>
              <span>-¥{data.totalPayable && data.totalPaid ? (data.totalPayable - data.totalPaid).toFixed(2) : '0.00'}</span>
            </div>
            <div className={styles.summaryRow}>
              <span>返现</span>
              <span>¥{data.totalCashback ? data.totalCashback.toFixed(2) : '0.00'}</span>
            </div>
            <div className={styles.summaryRow}>
              <span>押金</span>
              <span>¥{data.deposit ? data.deposit.toFixed(2) : '0.00'}</span>
            </div>
            <Divider dashed/>
            <div className={styles.summaryRowTotal}>
              <span>合计</span>
              <span className={styles.totalAmount}>
                 ¥{((data?.totalPaid || 0) + (data?.deposit || 0)).toFixed(2)}
              </span>
            </div>
          </div>

          <div className={styles.actionBar}>
            <Button
              type="primary"
              size="large"
              icon={<ShoppingCartOutlined/>}
              loading={loading}
              onClick={() => onSubmit(selectedAddress as API.ICustomerAddress)}
              block
            >
              确认下单
            </Button>
          </div>
        </Card>
      </div>
      <AddAddressForm
        visible={showAddressForm}
        onCancel={() => setShowAddressForm(false)}
        onSubmit={handleAddAddress}
      />
      <AddressSelection
        addresses={addresses}
        selectedAddress={selectedAddress}
        onSelect={handleAddressSelect}
        onAddNew={() => setShowAddressForm(true)}
        showAddressSelection={showAddressSelection}
        onOk={() => setShowAddressSelection(false)}
        onCancel={() => setShowAddressSelection(false)}
      />
    </>

  );
};

export default OrderInfo;
